﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;

namespace PlanningGIS.Util.Data
{
    /// <summary>
    /// 数据库对象操作的基类
    /// </summary>
    public abstract class DbContext
    {
        /// <summary>
        /// 获取或设置连接字符串
        /// </summary>
        public virtual string ConnectionString {
            get;
            set; }

        /// <summary>
        /// 是否自动关闭数据库，默认为自动关闭
        /// </summary>
        public virtual bool AutoClosed { get; set; }

        /// <summary>
        /// 获取数据库连接对象
        /// </summary>
        public virtual IDbConnection Connection { get; protected set; }

        /// <summary>
        /// 获取或设置执行的事务
        /// </summary>
        public virtual IDbTransaction Transaction { get; set; }
        
        /// <summary>
        /// 获取当前的数据库连接状态
        /// </summary>
        public virtual ConnectionState State
        {
            get
            {
                if (Connection == null) return ConnectionState.Broken;
                return Connection.State;
            }
        }

        /// <summary>
        /// 获取当前执行的消息
        /// </summary>
        public virtual string Message { get; protected set; }

        /// <summary>
        /// 获取所有满足条件的数据
        /// </summary>
        /// <typeparam name="T">数据实体对象</typeparam>
        /// <param name="parameters">条件参数</param>
        /// <param name="tablename">数据表名称，默认为实例对象的名称</param>
        /// <returns></returns>
        public virtual DataTable GetAll<T>(Dictionary<string, dynamic> parameters = null, string tablename = "")
        {
            if (string.IsNullOrWhiteSpace(tablename))
            {
                Type t = typeof(T);
                tablename = t.Name;
            }
            string sql = "select * from " + tablename;
            if (parameters != null && parameters.Count > 0)
            {
                sql = sql + " where " + GetWhereString(parameters);
            }
            return GetDataTable(sql, parameters);
        }

        /// <summary>
        /// 获取所有满足条件的数据实体对象
        /// </summary>
        /// <typeparam name="T">数据实体对象</typeparam>
        /// <param name="parameters">条件参数</param>
        /// <param name="tablename">数据表名称，默认为实例对象的名称</param>
        /// <returns></returns>
        public virtual List<T> GetAllEntry<T>(Dictionary<string, dynamic> parameters = null, string tablename = "")
        {
            DataTable dt = GetAll<T>(parameters, tablename);
            if (dt == null || dt.Rows.Count == 0) return null;
            return dt.ToObject<T>();
        }

        /// <summary>
        /// 根据条件参数获取查询条件语句
        /// </summary>
        /// <param name="wheres">条件参数</param>
        /// <returns></returns>
        protected string GetWhereString(Dictionary<string, dynamic> wheres)
        {
            if (wheres == null || wheres.Count == 0) return "";
            string where = "";
            foreach (KeyValuePair<string, dynamic> kvp in wheres)
            {
                string s = kvp.Key.Replace(":", "@");
                if (!s.StartsWith("@")) s = "@" + s;
                where += " and " + kvp.Key.Replace(":", "").Replace("@", "").Trim() + "=" + s;
            }
            if (!string.IsNullOrEmpty(where) && !string.IsNullOrWhiteSpace(where))
                where = where.Trim().Substring(3);
            return where;
        }

        /// <summary>
        /// 执行Sql查询语句，获取满足条件的数据表信息
        /// </summary>
        /// <param name="sql">要执行的Sql语句,或存储过程名称</param>
        /// <param name="parameters">参数信息，使用like时参数的值为'%值%'</param>
        /// <param name="cmdtype">命令类型</param>
        /// <returns>System.Data.DataTable</returns>
        public virtual DataTable GetDataTable(string sql, Dictionary<string, dynamic> parameters = null, CommandType cmdtype = CommandType.Text)
        {
            return null;
        }

        /// <summary>
        /// 根据唯一标识获取数据
        /// </summary>
        /// <param name="tablename">数据表名称</param>
        /// <param name="idvalue">唯一标识的值</param>
        /// <param name="idname">唯一标识的字段名称</param>
        /// <returns></returns>
        public virtual DataTable GetDataTableByID(string tablename, string idvalue, string idname = "id")
        {
            Dictionary<string, dynamic> w = new Dictionary<string, dynamic>();
            w.Add(":id", idvalue);
            return GetDataTable(" select * from " + tablename + " where " + idname + "=:id ", w);
        }

        /// <summary>
        /// 根据唯一标识获取对应实体对象的数据
        /// </summary>
        /// <typeparam name="T">数据实体对象</typeparam>
        /// <param name="idvalue">唯一标识的值</param>
        /// <param name="idname">唯一标识的字段名称</param>
        /// <param name="tablename">数据表名称，默认为实例对象的名称</param>
        /// <returns></returns>
        public virtual DataTable GetDataTableByID<T>(string idvalue, string idname = "id", string tablename = "")
        {
            if (string.IsNullOrWhiteSpace(tablename))
            {
                Type t = typeof(T);
                tablename = t.Name;
            }
            return GetDataTableByID(tablename, idvalue, idname);
        }

        /// <summary>
        /// 根据唯一标识获取对应实体对象的实例
        /// </summary>
        /// <typeparam name="T">数据实体对象</typeparam>
        /// <param name="idvalue">唯一标识的值</param>
        /// <param name="idname">唯一标识的字段名称</param>
        /// <param name="tablename">数据表名称，默认为实例对象的名称</param>
        /// <returns></returns>
        public virtual T GetEntryByID<T>(string idvalue, string idname = "id", string tablename = "")
        {
            DataTable dt = GetDataTableByID<T>(idvalue, idname, tablename);
            if (dt == null || dt.Rows.Count == 0) return default(T);
            return dt.ToObject<T>()[0];
        }

        /// <summary>
        /// 将动态对象T转成键值对
        /// </summary>
        /// <typeparam name="T">动态类型</typeparam>
        /// <param name="obj">类型实例</param>
        /// <param name="nonull">是否同时转换有为空的值，默认为true，不转换</param>
        /// <returns></returns>
        public virtual Dictionary<string, dynamic> ConvertT<T>(T obj, bool nonull = true)
        {
            Type t = typeof(T);
            FieldInfo[] fds = t.GetFields();
            PropertyInfo[] pis = t.GetProperties();
            Dictionary<string, dynamic> values = new Dictionary<string, dynamic>();
            foreach (PropertyInfo pi in pis)
            {
                if (!pi.CanRead || !pi.CanWrite) continue;
                string name = pi.Name.Trim();
                if (values.ContainsKey(name.ToUpper())) continue;
                object v = pi.GetValue(obj, null);
                if (nonull && (v == null || string.IsNullOrWhiteSpace(v.ToString()))) continue;
                values.Add(name.ToUpper(), v);
            }
            foreach (FieldInfo fi in fds)
            {
                string name = fi.Name;
                if (values.ContainsKey(name.ToUpper())) continue;
                object v = fi.GetValue(obj);
                if (nonull && v == null) continue;
                values.Add(name.ToUpper(), v);
            }
            return values;
        }

        /// <summary>
        /// 将数据列T转成键值对
        /// </summary>
        /// <param name="dr">要转换的数据列</param>
        /// <param name="nonull">是否同时转换有为空的值，默认为true，不转换</param>
        /// <returns></returns>
        public virtual Dictionary<string, dynamic> ConvertT(DataRow dr, bool nonull = true)
        {
            Dictionary<string, dynamic> values = new Dictionary<string, dynamic>();
            foreach (DataColumn dc in dr.Table.Columns)
            {
                string name = dc.ColumnName;
                object obj = dr[dc];
                if (nonull && (obj == null || string.IsNullOrWhiteSpace(obj.ToString()))) continue;
                values.Add(name.ToUpper(), obj);
            }
            return values;
        }

        /// <summary>
        /// 将数据列T转成键值对
        /// </summary>
        /// <param name="dr">要转换的数据列</param>
        /// <param name="nonull">是否同时转换有为空的值，默认为true，不转换</param>
        /// <returns></returns>
        public virtual Dictionary<string, dynamic> ConvertT(IDataReader dr, bool nonull = true)
        {
            Dictionary<string, dynamic> values = new Dictionary<string, dynamic>();
            int cnt = dr.FieldCount;
            if (!dr.Read()) return null;
            for (int i = 0; i < cnt; i++)
            {
                string name = dr.GetName(i);
                
                object obj = dr.GetValue(i);
                if (nonull && (obj == null || string.IsNullOrWhiteSpace(obj.ToString()))) continue;
                values.Add(name.ToUpper(), obj);
            }
            return values;
        }

        /// <summary>
        /// 创建事务对象，事务执行完成后注意要提交事务，并关闭数据库
        /// </summary>
        /// <returns></returns>
        public virtual void CreateTransaction()
        {
           
        }

        /// <summary>
        /// 将对象新增到数据库中
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">对象实例</param>
        /// <param name="tablename">数据表名称，默认为空，表示取对象的名称</param>
        /// <param name="checkfield">是否检查参数与表结构一致，若检查，则会将不一致的参数移除掉</param>
        /// <returns></returns>
        public virtual int Insert<T>(T obj, string tablename = "", bool checkfield = true)
        {
            if (string.IsNullOrWhiteSpace(tablename))
            {
                Type t = typeof(T);
                tablename = t.Name;
            }
            Dictionary<string, dynamic> values = new Dictionary<string, dynamic>();
            if (obj is DataTable)
            {
                DataTable dt = obj as DataTable;
                int n = 0;
                bool isAutoTran = (Transaction == null);
                if (isAutoTran) CreateTransaction();
                foreach (DataRow dr in dt.Rows)
                {
                    values = ConvertT(dr);
                    n += Insert(new List<string>() { tablename }, new List<List<Dictionary<string, dynamic>>>() { new List<Dictionary<string, dynamic>>() { values } }, checkfield);
                }
                if (isAutoTran) CommitTransaction();
                return n;
            }
            else if (obj is DataRow)
            {
                values = ConvertT(obj as DataRow);
            }
            else if (obj is IDataReader)
            {
                values = ConvertT(obj as IDataReader);
            }
            else
            {
                values = ConvertT<T>(obj);
            }
            return Insert(new List<string>() { tablename }, new List<List<Dictionary<string, dynamic>>>() { new List<Dictionary<string, dynamic>>() { values } }, checkfield);
        }

        /// <summary>
        /// 将一条数据插入到指定的数据表中
        /// </summary>
        /// <param name="tablename">要插入到的数据表</param>
        /// <param name="parameters">要新增的值</param>
        /// <param name="checkfield">是否检查参数与表结构一致，若检查，则会将不一致的参数移除掉</param>
        /// <returns></returns>
        public virtual int Insert(string tablename, Dictionary<string, dynamic> parameters, bool checkfield = true)
        {
            return Insert(new List<string>() { tablename }, new List<List<Dictionary<string, dynamic>>>() { new List<Dictionary<string, dynamic>>() { parameters } }, checkfield);
        }

        /// <summary>
        /// 将多条数据插入到一个数据表中
        /// </summary>
        /// <param name="tablename">要插入到的数据表</param>
        /// <param name="parameters">要新增的值</param>
        /// <param name="checkfield">是否检查参数与表结构一致，若检查，则会将不一致的参数移除掉</param>
        /// <returns></returns>
        public virtual int Insert(string tablename, List<Dictionary<string, dynamic>> parameters, bool checkfield = true)
        {
            return Insert(new List<string>() { tablename }, new List<List<Dictionary<string, dynamic>>>() { parameters }, checkfield);
        }

        /// <summary>
        /// 在每个数据表中插入一条指定的数据
        /// </summary>
        /// <param name="tablenames">要插入到的数据表</param>
        /// <param name="parameters">要新增的值</param>
        /// <param name="checkfield">是否检查参数与表结构一致，若检查，则会将不一致的参数移除掉</param>
        /// <returns></returns>
        public virtual int Insert(List<string> tablenames, List<Dictionary<string, dynamic>> parameters, bool checkfield = true)
        {
            List<List<Dictionary<string, dynamic>>> ps = new List<List<Dictionary<string, dynamic>>>();
            foreach (Dictionary<string, dynamic> itm in parameters)
            {
                ps.Add(new List<Dictionary<string, dynamic>>() { itm });
            }
            return Insert(tablenames, ps, checkfield);
        }        

        /// <summary>
        /// 在每个数据表中插入多条指定的数据
        /// </summary>
        /// <param name="tablenames">要插入到的数据表</param>
        /// <param name="parameters">要新增的值</param>
        /// <param name="checkfield">是否检查参数与表结构一致，若检查，则会将不一致的参数移除掉</param>
        /// <returns></returns>
        public virtual int Insert(List<string> tablenames, List<List<Dictionary<string, dynamic>>> parameters, bool checkfield = true)
        {
            return 0;
        }

        /// <summary>
        /// 根据数据表实例对象更新指定项的值
        /// </summary>
        /// <typeparam name="T">数据表实体对象</typeparam>
        /// <param name="obj">对象实例</param>
        /// <param name="keyfield">唯一主键，默认为id</param>
        /// <param name="keyvalue">主键的值，默认从obj实例中取值</param>
        /// <param name="nonull">是否只取不为空的值，默认为true</param>
        /// <param name="tablename">数据表名称，默认为空，表示取对象的名称</param>
        /// <returns></returns>
        public virtual int Update<T>(T obj, string keyfield = "id", string keyvalue = "", bool nonull = true, string tablename = "")
        {
            if (string.IsNullOrWhiteSpace(tablename))
            {
                Type t = typeof(T);
                tablename = t.Name;
            }
            Dictionary<string, dynamic> values = new Dictionary<string, dynamic>();
            Dictionary<string, dynamic> wheres = new Dictionary<string, dynamic>();
            if (obj is DataTable)
            {
                DataTable dt = obj as DataTable;
                int n = 0;
                bool isAutoTran = (Transaction == null);
                if (isAutoTran) CreateTransaction();
                foreach (DataRow dr in dt.Rows)
                {
                    values = ConvertT(dr, nonull);
                    wheres = new Dictionary<string, dynamic>();
                    wheres.Add(keyfield, values[keyfield.ToUpper()]);
                    n += Update(new List<string>() { tablename }, new List<Dictionary<string, dynamic>>() { values }, new List<Dictionary<string, dynamic>>() { wheres }, true); 
                }
                if (isAutoTran) CommitTransaction();
                return n;
            }
            else if (obj is DataRow)
            {
                values = ConvertT(obj as DataRow, nonull);
            }
            else if (obj is IDataReader)
            {
                values = ConvertT(obj as IDataReader);
            }
            else
            {
                values = ConvertT<T>(obj, nonull);                                
            }
            if (string.IsNullOrWhiteSpace(keyvalue)) keyvalue = values[keyfield.ToUpper()];
            wheres.Add(keyfield, keyvalue);
            return Update(new List<string>() { tablename }, new List<Dictionary<string, dynamic>>() { values }, new List<Dictionary<string, dynamic>>() { wheres }, true);
        }

        /// <summary>
        /// 更新数据表中满足条件的记录
        /// </summary>
        /// <param name="tablename">要更新的数据表</param>
        /// <param name="values">更新的值</param>
        /// <param name="wheres">满足的条件</param>
        /// <param name="checkfield">是否检查参数与表结构一致，若检查，则会将不一致的参数移除掉</param>
        /// <returns></returns>
        public virtual int Update(string tablename, Dictionary<string, dynamic> values, Dictionary<string, dynamic> wheres, bool checkfield = true)
        {
            return Update(new List<string>() { tablename }, new List<Dictionary<string, dynamic>>() { values }, new List<Dictionary<string, dynamic>>() { wheres }, checkfield);
        }

        /// <summary>
        /// 更新单个数据表中满足条件的记录
        /// </summary>
        /// <param name="tablename">要更新的数据表</param>
        /// <param name="values">更新的值</param>
        /// <param name="where">自定义的条件</param>
        /// <param name="whereparameters">自定义条件中的参数</param>
        /// <param name="checkfield">是否检查参数与表结构一致，若检查，则会将不一致的参数移除掉</param>
        /// <returns></returns>
        public virtual int Update(string tablename, Dictionary<string, dynamic> values, string where, Dictionary<string, dynamic> whereparameters, bool checkfield = true)
        {
            return Update(
                new List<string>() { tablename },
                new List<Dictionary<string, dynamic>>() { values },
                new List<string>() { where },
                new List<Dictionary<string, dynamic>>() { whereparameters },
                checkfield);
        }

        /// <summary>
        /// 更新多个数据表中满足条件的记录
        /// </summary>
        /// <param name="tablenames">要更新的数据表集合</param>
        /// <param name="values">更新的值</param>
        /// <param name="wheres">满足的条件</param>
        /// <param name="checkfield">是否检查参数与表结构一致，若检查，则会将不一致的参数移除掉</param>
        /// <returns></returns>
        public virtual int Update(List<string> tablenames, List<Dictionary<string, dynamic>> values, Dictionary<string, dynamic> wheres, bool checkfield = true)
        {
            List<Dictionary<string, dynamic>> ps = null;
            if (wheres != null && wheres.Count > 0)
            {
                ps = new List<Dictionary<string, dynamic>>();
                for (int i = 0; i < tablenames.Count; i++)
                {
                    ps.Add(wheres);
                }
            }
            return Update(tablenames, values, ps, checkfield);
        }

        /// <summary>
        /// 更新多个数据表中满足条件的记录
        /// </summary>
        /// <param name="tablenames">要更新的数据表集合</param>
        /// <param name="values">更新的值</param>
        /// <param name="where">自定义的条件</param>
        /// <param name="whereparameter">自定义条件中的参数</param>
        /// <param name="checkfield">是否检查参数与表结构一致，若检查，则会将不一致的参数移除掉</param>
        /// <returns></returns>
        public virtual int Update(List<string> tablenames, List<Dictionary<string, dynamic>> values, string where, Dictionary<string, dynamic> whereparameter, bool checkfield = true)
        {
            int count = tablenames.Count;
            List<string> wheres = null;
            if (!string.IsNullOrEmpty(where) || !string.IsNullOrWhiteSpace(where))
            {
                wheres = new List<string>();
                for (int i = 0; i < count; i++)
                {
                    wheres.Add(where);
                }
            }
            List<Dictionary<string, dynamic>> ps = null;
            if (whereparameter != null && whereparameter.Count > 0)
            {
                ps = new List<Dictionary<string, dynamic>>();
                for (int i = 0; i < count; i++)
                {
                    ps.Add(whereparameter);
                }
            }
            return Update(tablenames, values, wheres, ps, checkfield);
        }
        
        /// <summary>
        /// 更新多个数据表中满足条件的记录
        /// </summary>
        /// <param name="tablenames">要更新的数据表集合</param>
        /// <param name="values">更新的值</param>
        /// <param name="wheres">满足的条件</param>
        /// <param name="checkfield">是否检查参数与表结构一致，若检查，则会将不一致的参数移除掉</param>
        /// <returns></returns>
        public virtual int Update(List<string> tablenames, List<Dictionary<string, dynamic>> values, List<Dictionary<string, dynamic>> wheres, bool checkfield = true)
        {
            return 0;
        }
        
        /// <summary>
        /// 更新多个数据表中满足条件的记录
        /// </summary>
        /// <param name="tablenames">要更新的数据表集合</param>
        /// <param name="values">更新的值</param>
        /// <param name="wheres">自定义的条件</param>
        /// <param name="whereparameters">自定义条件中的参数</param>
        /// <param name="checkfield">是否检查参数与表结构一致，若检查，则会将不一致的参数移除掉</param>
        /// <returns></returns>
        public virtual int Update(List<string> tablenames, List<Dictionary<string, dynamic>> values, List<string> wheres, List<Dictionary<string, dynamic>> whereparameters, bool checkfield = true)
        {
            return 0;
        }
        
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="tablename">数据表名称</param>
        /// <param name="where">要删除的条件值，以等于判断。为空时表示删除所有的数据</param>
        /// <returns></returns>
        public virtual int Delete(string tablename, Dictionary<string, dynamic> where = null)
        {
            return 0;
        }

        /// <summary>
        /// 删除指定编号的数据信息
        /// </summary>
        /// <param name="tablename">数据表名称</param>
        /// <param name="idvalue">编号的值</param>
        /// <param name="idname">编号字段名称，默认为id</param>
        /// <returns></returns>
        public virtual int Delete(string tablename, string idvalue, string idname = "id")
        {
            Dictionary<string, dynamic> where = new Dictionary<string, dynamic>();
            where.Add(idname, idvalue);
            return Delete(tablename, where);
        }


        /// <summary>
        /// 删除数据表中指定编号的记录
        /// </summary>
        /// <param name="tablename">数据表名称</param>
        /// <param name="ids">编号集合</param>
        /// <param name="idname">编号字段名称，默认为id</param>
        /// <returns></returns>
        public virtual int Delete(string tablename, List<string> ids, string idname = "id")
        {
            if (ids == null || ids.Count == 0) return 0;
            if (string.IsNullOrWhiteSpace(tablename) || string.IsNullOrWhiteSpace(idname)) return -1;
            string sql = string.Format("delete from {0} where {1} = :id", tablename, idname);            
            List<Dictionary<string, dynamic>> parameters = new List<Dictionary<string, dynamic>>();
            foreach (string id in ids)
            {
                Dictionary<string, dynamic> p = new Dictionary<string, dynamic>();
                p.Add(":id", id);
                parameters.Add(p);
            }
            return ExecuteNonQuery(sql, parameters);
        }


        /// <summary>
        /// 删除指定表中满足指定字段值的数据
        /// </summary>
        /// <param name="tablenames">数据表名称</param>
        /// <param name="values">值</param>
        /// <param name="fields">字段</param>
        /// <returns></returns>
        public virtual int Delete(List<string> tablenames, List<string> values, List<string> fields)
        {
            List<string> sqls = new List<string>();
            List<Dictionary<string, dynamic>> ps = new List<Dictionary<string, dynamic>>();
            for (int i = 0; i < tablenames.Count; i++)
            {
                Dictionary<string, dynamic> p = new Dictionary<string, dynamic>();
                sqls.Add("delete from " + tablenames[i] + " where " + fields[i] + " = :id ");
                p.Add(":id", values[i]);
                ps.Add(p);
            }
            return ExecuteNonQuery(sqls, ps);
        }

        /// <summary>
        /// 删除多个表中字段字段值为id的记录
        /// </summary>
        /// <param name="id">值</param>
        /// <param name="tablefields">数据表及对应的字段：table，field</param>
        /// <returns></returns>
        public virtual int Delete(string id, Dictionary<string, string> tablefields)
        {
            List<string> sqls = new List<string>();
            List<Dictionary<string, dynamic>> ps = new List<Dictionary<string, dynamic>>();
            foreach (KeyValuePair<string, string> kvp in tablefields)
            {
                Dictionary<string, dynamic> p = new Dictionary<string, dynamic>();
                sqls.Add("delete from " + kvp.Key + " where " + kvp.Value + " = :id ");
                p.Add(":id", id);
                ps.Add(p);
            }
            return ExecuteNonQuery(sqls, ps);
        }

        /// <summary>
        /// 执行 SQL 语句并返回受影响的行数。
        /// </summary>
        /// <param name="sql">SQL 语句。</param>
        /// <param name="parameters">参数信息，使用like时参数的值为'%值%'</param>
        /// <param name="cmdtype">命令类型</param>
        /// <returns>受影响的行数。</returns>
        public virtual int ExecuteNonQuery(string sql, Dictionary<string, dynamic> parameters = null, CommandType cmdtype = CommandType.Text)
        {
            return 0;
        }

        /// <summary>
        /// 在数据库事务中将一条 SQL 语句执行多次。
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters">参数信息，使用like时参数的值为'%值%'</param>
        /// <param name="cmdtype">命令类型</param>
        /// <returns>影响的记录条数。</returns>
        public virtual int ExecuteNonQuery(string sql, List<Dictionary<string, dynamic>> parameters, CommandType cmdtype = CommandType.Text)
        {
            return 0;
        }

        /// <summary>
        /// 在数据库事务中执行多条 SQL 语句。
        /// </summary>
        /// <param name="sqls">多条 SQL 语句</param>
        /// <param name="parameters">参数信息，使用like时参数的值为'%值%'</param>
        /// <param name="cmdtype">命令类型</param>
        /// <returns>影响的记录条数。</returns>
        public virtual int ExecuteNonQuery(List<string> sqls, List<Dictionary<string, dynamic>> parameters = null, CommandType cmdtype = CommandType.Text)
        {
            return 0;
        }

        /// <summary>
        /// 提交事务，没有关闭数据库，若需要关闭，则调用Close进行关闭。
        /// </summary>
        public void CommitTransaction()
        {
            AutoClosed = true;
            if (Transaction != null)
            {
                Transaction.Commit();
                Transaction.Dispose();
                Transaction = null;
            }
        }

        /// <summary>
        /// 回滚提交事务
        /// </summary>
        public void RollbackTransaction()
        {
            AutoClosed = true;
            if (Transaction != null)
            {
                Transaction.Rollback();
                Transaction.Dispose();
                Transaction = null;
            }
        }

        /// <summary>
        /// 关闭数据库
        /// </summary>
        public void Close()
        {
            try
            {
                if (this.Connection != null && Connection.State != ConnectionState.Closed)
                {
                    this.Connection.Close();
                }
            }
            catch
            {

            }
        }
        
    }
}
